<?php

namespace Modules\User\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\User\Entities\User;

use Validator;
use ThrowException;
use Auth;
use Setting;
use SMS;
use Miniapp;
use Storage;

class CurrentUserController extends Controller
{
    // 当前登陆的用户信息
    public function show(Request $req)
    {
        $user = Auth::requireLoginUser();

        $info = $user->getInfo([
            'id',
            'uuid',
            'name',
            'gender',
            'phone',
            'city',
            'email',
            'birthday',
            'headimg',
            'new_headimg',
            'invite_code',
            'invite_id',
            'invite_poster',
            'vip_status',
            'vip_end_at'
        ]);

        if ($user->inviter) {
            $info['inviter'] = $user->inviter->getInfo([
                'name'
            ]);
        }

        // $count = $user->sign_in_records()->count();
        // $tipsText = '每天签到可获得' . config('asset.score.signin_award') . '幸运值';

        // foreach (config('asset.score.signin_other_award') as $day => $value) {
        //     if ($day > $count) {
        //         $tipsText = '累计签到' . $day . '天可额外获得' . $value . '幸运值';
        //         break;
        //     }
        // }

        // $elf = $user->getCurrentElf();

        // if ($elf)
        //     $elf = $elf->getInfo([
        //         'title',
        //         'default_image',
        //         'animation_gif'
        //     ]);

        $info = array_merge($info, [
            'score' => $user->asset('score')->balance,
            'redpack' => $user->asset('redpack')->balance,
            'card_total' => $user->getCardTotal(),
            'working_activity' => 0,
            // 'working_activity' => $user->activities()->status('working')->count(),
            // 'max_score' => '100',
            // 'is_signed_in' => $user->isSignedIn() ? 1 : 0,
            // 'is_signed_in' => 0,
            // 'sign_in_day' => $count,
            // 'tips_text' => $tipsText,
            // 'current_elf' => $elf,
            // 'pet_bg' => Setting::get('pet_bg'),
            'chip_count' => $user->chip_assets()->sum('balance'),
            'coupon_count' => $user->coupons()->valid()->count(),
            'invitees_count' => User::inviteBy($user)->count()
        ]);

        return [
            'user' => $info
        ];
    }

    // 小程序授权修改手机号
    public function update(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        if (!$req->input('name')) {
            ThrowException::Conflict('请填写姓名~');
        }

        $name = $req->name;
        $name = str_replace(' ', '', $name);
        $name = str_replace(' ', '', $name);
        if (!$name) {
            ThrowException::Conflict('姓名不能为空~');
        }

        if (mb_strlen($name) > 8) {
            ThrowException::Conflict('名字控制在8个字以内哦~');
        }

        $user = Auth::requireLoginUser();

        $info = $req->all();

        $user->update($info);

        return [
        ];
    }


    public function updateHeadImg(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $image = $req->image;

        $disk = Storage::disk();

        // 前缀 or 目录
        $dir = '/img/' . $req->input('dir', 'other');

        $path = $disk->put($dir, $image);
        $path = $disk->url($path);

        $user = Auth::requireLoginUser();

        $user->headimg = $path;
        $user->new_headimg = $path;

        $user->save();
    }

    // 申请注销
    public function destroy(Request $req)
    {
        $user = Auth::requireLoginUser();
        if ($user->require_delete_at) {
            ThrowException::Conflict('已申请过，耐心等待客服审核哦~');
        }
        $user->update([
            'require_delete_at' => now()
        ]);

        return [];
    }

    // 绑定邀请码
    public function bindInviter(Request $req)
    {
        $rule = [
            'invite_code' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $flag = @Setting::get('sys_invite')['is_bind_inviter_manual_enabled'];

        if (!$flag) {
            ThrowException::Conflict('当前不允许手动绑定邀请码~');
        }

        $user = Auth::requireLoginUser();

        if ($user->inviter_id) {
            ThrowException::Conflict('你已绑定过邀请者，无法重复绑定~');
        }

        if ($user->invite_code === $req->invite_code) {
            ThrowException::Conflict('不能绑定自己哦~');
        }

        $inviter = User::where('invite_code', $req->invite_code)->first() ?: ThrowException::Conflict('邀请码不存在~');

        if ($inviter->isBlocked()) {
            ThrowException::Conflict('用户异常~');
        }

        // 绑定用户
        $user->bindInviter($inviter, $req);

        return [];
    }

    // 小程序授权修改手机号
    public function updatePhoneWithMiniapp(Request $req)
    {
        $rule = [
            'iv' => ['required'],
            'encrypt_data' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $data = Miniapp::get()->getUserInfo($req->code, $req->iv, $req->encrypt_data);

        $phone = @$data['purePhoneNumber'] ?: ThrowException::Conflict('获取手机号失败');

        // 首次绑定手机号
        $firstBindPhone = $user->phone ? false : true;

        $user->update([
            'phone' => $phone
        ]);

        // 注册赠送积分
        if ($firstBindPhone) {
            $bindPhoneReward = @Setting::get('sys_score')['bind_phone_reward'] ?: 0;
            if ($bindPhoneReward) {
                $user->asset('score')->in($bindPhoneReward, [
                    'description' => '首次绑定手机号赠送'
                ]);
            }
        }

        return [
        ];
    }

    // 小程序授权修改手机号
    public function updatePhoneWithCode(Request $req)
    {
        $rule = [
            'phone' => ['required'],
            'phone_code' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        
        if (strlen($req->phone) !== 11) {
            ThrowException::Conflict('手机号格式不正确~');
        }

        $phone = $req->phone;
        SMS::verifyCode($req->phone, $req->phone_code, 'login') || ThrowException::Conflict('验证码不正确');

        // 首次绑定手机号
        $firstBindPhone = $user->phone ? false : true;

        $user->update([
            'phone' => $phone
        ]);

        // 注册赠送积分
        if ($firstBindPhone) {
            $bindPhoneReward = @Setting::get('sys_score')['bind_phone_reward'] ?: 0;
            if ($bindPhoneReward) {
                $user->asset('score')->in($bindPhoneReward, [
                    'description' => '首次绑定手机号赠送'
                ]);
            }
        }

        return [
        ];
    }
}
